angular.module('furion.controllers.home', [])

.controller 'HomeCtrl', ($scope, $ionicModal, $ionicSideMenuDelegate, RemoteSrv, $state, $ionicSlideBoxDelegate, $ImageCacheFactory, $timeout, ClubInfo, FriendsInfo) ->
  $scope.cur_page = 0
  $scope.max_page = 1
  $scope.limit = 5
  $scope.all_data = []
  $scope.level_num = []

  $scope.goPage = (page)->
    return if page > $scope.max_page
    $scope.list = []
    # min = ((page-1)*$scope.limit)
    max = (page*$scope.limit-1)
    # last = $scope.list.length - 1
    # if max < last
    #   max = last
    #   console.log max
    for i in [0..max]
      break if !$scope.all_data[i]
      $scope.list.push $scope.all_data[i]
    $scope.cur_page = page

  $scope.getMoreList = (page)->
    $scope.$emit "loading:show" unless $scope.list
    $scope.all_data = $scope.Infos
    $scope.size = $scope.all_data.length
    $scope.max_page = parseInt($scope.size / $scope.limit)
    $scope.max_page += 1 if $scope.size % $scope.limit != 0
    $scope.goPage(page)
    
    $timeout ()->
      $scope.$emit "loading:hide"
      $scope.$broadcast('scroll.refreshComplete')
      $scope.$broadcast('scroll.infiniteScrollComplete')
    , 1000

    return

  $scope.changeType = (num)->
    if num == 'amateur'
      $scope.Infos = FriendsInfo.allD
      $scope.type = 'amateur'
    else if num == 'club'
      $scope.Infos = ClubInfo.allD
      $scope.type = 'club'
      for i,index in $scope.Infos
        console.log index
        $scope.level_num[index] = new Array(i.level)
    $scope.getMoreList(1)

  $scope.$on '$ionicView.enter', ()->
    return unless !$scope.Infos
    $scope.type ||= 'amateur'
    $scope.changeType('amateur')

    $scope.list = []
    $scope.getMoreList(1)

  return

.controller 'DynamicDetailCtrl', ($scope, $state, $stateParams, ClubInfo, FriendsInfo, Geolocation) ->
  $scope.data = {}
  $scope.geolocation = Geolocation.getPosition()
  # $scope.level_num = []
  $scope.type = $stateParams.type

  $scope.$on '$ionicView.enter', ()->
    if $stateParams.type == 'amateur'
      $scope.data = FriendsInfo.getF($stateParams.id)
    else
      $scope.data = ClubInfo.getC($stateParams.id)
      $scope.level_num = new Array($scope.data.level)
      $scope.getLocation($scope.data.location.longitude, $scope.data.location.latitude)  

  $scope.getLocation = (long, la)->
    map = new BMap.Map("map-content")
    PointA = new BMap.Point($scope.geolocation.longitude, $scope.geolocation.latitude)
    Point = new BMap.Point(long,la)
    console.debug Point
    console.debug PointA
    map.centerAndZoom(Point, 20)
    marker = new BMap.Marker(Point)  # 创建标注
    map.addOverlay(marker)
    $scope.data.distance = (map.getDistance(PointA, Point)).toFixed(0)
    console.debug $scope.data.distance

  $scope.contact = (p)->
    window.location = "tel:" + p

  return